﻿using System;
using System.Collections.Generic;
using System.Data.Objects.DataClasses;
using System.Diagnostics;
using System.Linq;
using System.Security.Authentication;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using GameSchool.DAL;
using GameSchool.Models;
using GameSchool.Models.AccountModels;
using GameSchool.Models.ExamModels;
using GameSchool.ViewModels.Exam;

namespace GameSchool.Controllers
{
    public class ExamController : Controller
    {
        private IExamRepository m_rep;

        public ExamController()
        {
            m_rep = new ExamRepository(new gsEntities());
        }

        public ExamController(IExamRepository rep)
        {
            m_rep = rep;
        }

        [Authorize(Roles = "Kennari")]
        public PartialViewResult AddQuestion(int id)
        {
            return PartialView("AddQuestionPartial", new ExamQuestionModel()
                                                         {
                                                             ExamQuestionNo = id
                                                         });
        }

        [Authorize(Roles = "Kennari")]
        public ActionResult Create(int id)
        {
            // Búa til viewmodel
            var viewModel = new CreateViewModel();
            viewModel.currentCourse = m_rep.GetCourseById(id);

            return View(viewModel);
        }

        [HttpPost]
        [Authorize(Roles = "Kennari")]
        public ActionResult Create(int id, ExamModel exam)
        {
            var examToCreate = exam.ToExamEntity();
            examToCreate.CourseID = id;
            examToCreate.TeacherUserID = (Guid)Membership.GetUser().ProviderUserKey;

            m_rep.InsertExam(examToCreate);
            m_rep.Save();

            return RedirectToAction("List", new { id });
        }

        [Authorize(Roles = "Kennari, Nemandi")]
        public ActionResult Details(int id)
        {
            var viewModel = new DetailsViewModel();
            viewModel.examHistory = m_rep.GetExamHistoryById(id);
            viewModel.currentCourse = m_rep.GetCourseById(viewModel.examHistory.Exam.CourseID);
            viewModel.exam = new ExamModel(m_rep.GetExamById(viewModel.examHistory.ExamID));

            return View(viewModel);
        }

        [Authorize(Roles = "Kennari, Nemandi")]
        public ActionResult List(int id)
        {
            var viewModel = new ListViewModel();
            viewModel.currentCourse = m_rep.GetCourseById(id);

            if (User.IsInRole("Kennari"))
            {
                viewModel.examsTeacher = m_rep.GetExamsTeacher(id, (Guid)Membership.GetUser().ProviderUserKey);
                return View("ListTeacher", viewModel);
            }
            else if (User.IsInRole("Nemandi"))
            {
                viewModel.examsStudent = m_rep.GetExamsStudent(id, (Guid)Membership.GetUser().ProviderUserKey);
                return View("ListStudent", viewModel);
            }

            throw new AuthenticationException("Obbossí, þú virðist ekki vera í neinni grúppu sem gefur þér aðgang hingað inn. Hvernig komstu hingað?");
        }

        [Authorize(Roles = "Kennari")]
        public ActionResult Results(int id)
        {
            var viewModel = new ResultsViewModel();
            viewModel.currentCourse = m_rep.GetExamById(id).Course;
            viewModel.currentExam = m_rep.GetExamById(id);
            viewModel.examsStudents = m_rep.GetExamsStudent(id);

            return View(viewModel);
        }

        [Authorize(Roles = "Nemandi")]
        public ActionResult SubmitAnswers(int id)
        {
            var examToSubmit = m_rep.GetExamById(id);

            var viewModel = new SubmitAnswersViewModel();
            viewModel.currentCourse = m_rep.GetCourseById(examToSubmit.CourseID);
            viewModel.exam = new ExamModel(examToSubmit);

            return View(viewModel);
        }

        [HttpPost]
        [Authorize(Roles = "Nemandi")]
        public ActionResult SubmitAnswers(int id, ExamModel exam)
        {
            var entityExam = m_rep.GetExamById(id);
            int questionCount = entityExam.ExamQuestion.Count;
            int correctAnswers = 0;


            // Byggja upp prófið í Entity Módel formi
            var eh = new ExamHistory
                         {
                             ExamID = id,
                             StudentUserID = (Guid)Membership.GetUser().ProviderUserKey,
                             SubmitDate = DateTime.Now,
                             ExamHistoryAnswers = new EntityCollection<ExamHistoryAnswers>()
                         };

            // Byggja upp svörin og setja inn í prófið
            foreach (var q in exam.ExamQuestions)
            {
                eh.ExamHistoryAnswers.Add(new ExamHistoryAnswers()
                                              {
                                                  AnswerID = q.CorrectAnswerIsNo
                                              });

                // Athuga hvort svarið hafi verið rétt og bæta við teljarann ef svo er
                if (m_rep.CheckIfAnswerIsCorrect(q.CorrectAnswerIsNo))
                {
                    correctAnswers = correctAnswers + 1;
                }
            }

            // Reikna út einkunnina
            var grade = ((double)correctAnswers / (double)questionCount) * 10.0;
            eh.Grade = grade;

            // Skella öllu inn í töfluna
            m_rep.InsertExamHistoryAnswers(eh);
            m_rep.Save();

            return RedirectToAction("List", new { id = entityExam.CourseID });
        }

        [Authorize(Roles = "Kennari")]
        public ActionResult View(int id)
        {
            var examToView = m_rep.GetExamById(id);

            var viewModel = new ViewViewModel();
            viewModel.currentCourse = m_rep.GetCourseById(examToView.CourseID);
            viewModel.exam = new ExamModel(examToView);

            return View(viewModel);
        }
    }
}
